#include <ESP8266WiFi.h>
#include "mywifi_manager.h"
#include <PubSubClient.h>
// LED 引脚
#define PIN_led  2// 根据实际情况修改引脚

// MQTT 服务器配置
const char* mqttServer = "broker-cn.emqx.io";
const int mqttPort = 1883;

// 主题
const char* topic = "LEDTEST";
long lastMsg = 0;

    String clientId = "ESP8266Client-";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(115200);
  pinMode(PIN_led, OUTPUT);
  digitalWrite(PIN_led, HIGH); // 默认关闭 LED

    clientId += String(WiFi.macAddress());
  // 连接 WiFi
setupWiFi();

  // 设置 MQTT 服务器
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);

  // 连接到 MQTT
  reconnect();
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  
  long now = millis();
  if (now - lastMsg > 60000) {
    lastMsg = now;
    client.publish("LEDTEST", clientId.c_str());
  }

}

// 连接到 MQTT 服务器
void reconnect() {
  // 尝试连接
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");

    
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      client.subscribe(topic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 1 second");
      delay(1000); // 适当的短延迟
    }
  }
}

// MQTT 消息回调函数
void callback(char* topic, byte* payload, unsigned int length) {
  String message;
  for (int i = 0; i < length; i++) {
    message += (char)payload[i];
  }

  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("]: ");
  Serial.println(message);

  if (message == "1") {
    digitalWrite(PIN_led, LOW); // 打开 LED
// client.publish(topic, "LED已打开");
  } 
  else if(message == "0"){
    digitalWrite(PIN_led, HIGH); // 关闭 LED
    // client.publish(topic, "LED已关闭");
  }
  
}
